/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ar.com.neolokura.travian.helper.world.admin;

import ar.com.neolokura.travian.helper.bo.item.OasisItem;
import ar.com.neolokura.travian.helper.browser.admin.BrowserAdmin;
import com.zenkey.net.prowser.Tab;
import java.util.ArrayList;
import org.apache.log4j.Logger;

/**
 *
 * @author gustavo
 */
public class WorldAdmin {

    private static Logger logger = Logger.getLogger(WorldAdmin.class.getSimpleName());
    private static WorldAdmin INSTANCE = null;

    // Private constructor suppresses 
    private WorldAdmin() {
        logger.info(">> WorldAdmin started...");
    }

    // creador sincronizado para protegerse de posibles problemas  multi-hilo
    // otra prueba para evitar instanciación múltiple 
    private synchronized static void createInstance() {
        if (INSTANCE == null) {
            INSTANCE = new WorldAdmin();
        }
    }

    public static WorldAdmin getInstance() {
        if (INSTANCE == null) {
            createInstance();
        }
        return INSTANCE;
    }

    public ArrayList<OasisItem> getAllOasis(Integer x, Integer y, Integer tilesAway) {
        //TODO: copy from FullOasis

        BrowserAdmin browserAdmin = BrowserAdmin.getInstance();
        Tab tab = browserAdmin.getTabInstance();
        
        WorldParser parser = new WorldParser();
        ArrayList<OasisItem> oasisList = new ArrayList<OasisItem>();
        for (int i = x - tilesAway; i < x + tilesAway; i++) {
            for (int j = y - tilesAway; j < y + tilesAway; j++) {
                tab.go("http://ts6.travian.cl/ajax.php?cmd=viewTileDetails&x=" + i + "&y=" + j);
                System.out.println("Searching: " + i + " " + j);
                OasisItem oasis = parser.getOasisFromJson(tab.getPageSource(), i, j);
                if (oasis != null) {

                    Integer xDist = x - i;
                    Integer yDist = y - j;
                    xDist = xDist * xDist;
                    yDist = yDist * yDist;
                    Double dist = Math.sqrt(xDist + yDist);

                    oasisList.add(oasis);
                }
            }

        }
        return oasisList;
    }
}
